<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="guava,cache,example,示例" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="1.使用场景 缓存在很多场景下都是相当有用的。例如，计算或检索一个值的代价很高，并且对同样的输入需要不止一次获取值的时候，就应当考虑使用缓存。   Guava Cache与ConcurrentMap很相似，但也不完全一样。最基本的区别是ConcurrentMap会一直保存所有添加的元素，直到显式地移除。相对地，Guava Cache为了限制内存占用，通常都设定为自动回收元素。在某些场景下，尽管Lo">
<meta name="keywords" content="guava,cache,example,示例">
<meta property="og:type" content="article">
<meta property="og:title" content="Guava Cache使用示例">
<meta property="og:url" content="http://www.zhizus.com/2016-11-05guava-cache-info.html">
<meta property="og:site_name" content="郑大侠的博客">
<meta property="og:description" content="1.使用场景 缓存在很多场景下都是相当有用的。例如，计算或检索一个值的代价很高，并且对同样的输入需要不止一次获取值的时候，就应当考虑使用缓存。   Guava Cache与ConcurrentMap很相似，但也不完全一样。最基本的区别是ConcurrentMap会一直保存所有添加的元素，直到显式地移除。相对地，Guava Cache为了限制内存占用，通常都设定为自动回收元素。在某些场景下，尽管Lo">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-28T02:35:39.666Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Guava Cache使用示例">
<meta name="twitter:description" content="1.使用场景 缓存在很多场景下都是相当有用的。例如，计算或检索一个值的代价很高，并且对同样的输入需要不止一次获取值的时候，就应当考虑使用缓存。   Guava Cache与ConcurrentMap很相似，但也不完全一样。最基本的区别是ConcurrentMap会一直保存所有添加的元素，直到显式地移除。相对地，Guava Cache为了限制内存占用，通常都设定为自动回收元素。在某些场景下，尽管Lo">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: "",
      labels: ""
    }
  };
</script>



  <link rel="canonical" href="http://www.zhizus.com/2016-11-05guava-cache-info.html"/>





  <title> Guava Cache使用示例 | 郑大侠的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f75c9cec9ecead0dfce9a108b9688072";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">郑大侠的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-crossed">
          <a href="http://zhizus.com" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br />
            
            穿越
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.zhizus.com/2016-11-05guava-cache-info.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="DempeZheng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郑大侠的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Guava Cache使用示例
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2016-11-05guava-cache-info.html" class="leancloud_visitors" data-flag-title="Guava Cache使用示例">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-使用场景"><a href="#1-使用场景" class="headerlink" title="1.使用场景"></a>1.使用场景</h2><blockquote>
<p>缓存在很多场景下都是相当有用的。例如，计算或检索一个值的代价很高，并且对同样的输入需要不止一次获取值的时候，就应当考虑使用缓存。</p>
</blockquote>
<blockquote>
<p>Guava Cache与ConcurrentMap很相似，但也不完全一样。最基本的区别是ConcurrentMap会一直保存所有添加的元素，直到显式地移除。相对地，Guava Cache为了限制内存占用，通常都设定为自动回收元素。在某些场景下，尽管LoadingCache 不回收元素，它也是很有用的，因为它会自动加载缓存。</p>
</blockquote>
<p>通常来说，Guava Cache适用于：</p>
<ul>
<li>你愿意消耗一些内存空间来提升速度。</li>
<li>你预料到某些键会被查询一次以上。</li>
<li>缓存中存放的数据总量不会超出内存容量。（Guava Cache是单个应用运行时的本地缓存。它不把数据存放到文件或外部服务器。如果这不符合你的需求，请尝试Memcached这类工具）</li>
</ul>
<p>如果你的场景符合上述的每一条，Guava Cache就适合你。</p>
<p>如同范例代码展示的一样，Cache实例通过CacheBuilder生成器模式获取，但是自定义你的缓存才是最有趣的部分。</p>
<p>注：如果你不需要Cache中的特性，使用ConcurrentHashMap有更好的内存效率——但Cache的大多数特性都很难基于旧有的ConcurrentMap复制，甚至根本不可能做到。</p>
<h2 id="2-如何使用Guava-Cache"><a href="#2-如何使用Guava-Cache" class="headerlink" title="2.如何使用Guava Cache"></a>2.如何使用Guava Cache</h2><p>下面我们以一个简单的例子开始，缓存大写的字符串key。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">whenCacheMiss_thenValueIsComputed</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">       CacheLoader&lt;String, String&gt; loader;</span><br><span class="line">       loader = <span class="keyword">new</span> CacheLoader&lt;String, String&gt;() &#123;</span><br><span class="line">           <span class="comment">// 当guava cache中不存在，则会调用load方法</span></span><br><span class="line">           <span class="meta">@Override</span></span><br><span class="line">           <span class="function"><span class="keyword">public</span> String <span class="title">load</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;;</span><br><span class="line"></span><br><span class="line">       LoadingCache&lt;String, String&gt; cache;</span><br><span class="line">       cache = CacheBuilder</span><br><span class="line">               .newBuilder()</span><br><span class="line">               <span class="comment">// 写数据1s后重新加载缓存</span></span><br><span class="line">               .refreshAfterWrite(<span class="number">1L</span>, TimeUnit.SECONDS)</span><br><span class="line">               .build(loader);</span><br><span class="line"></span><br><span class="line">       assertEquals(<span class="number">0</span>, cache.size());</span><br><span class="line">       cache.put(<span class="string">"test"</span>, <span class="string">"test"</span>);</span><br><span class="line">       assertEquals(<span class="string">"test"</span>, cache.getUnchecked(<span class="string">"test"</span>));</span><br><span class="line">       assertEquals(<span class="string">"HELLO"</span>, cache.getUnchecked(<span class="string">"hello"</span>));</span><br><span class="line">       assertEquals(<span class="number">2</span>, cache.size());</span><br><span class="line"></span><br><span class="line">       TimeUnit.SECONDS.sleep(<span class="number">2</span>);</span><br><span class="line">       assertEquals(<span class="string">"TEST"</span>, cache.getUnchecked(<span class="string">"test"</span>));</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-回收策略"><a href="#3-回收策略" class="headerlink" title="3.回收策略"></a>3.回收策略</h2><p>所有的cache都需要定期remove value，下面我们看看guava cache的回收策略。</p>
<h3 id="3-1-基于容量的回收-Eviction-by-Size"><a href="#3-1-基于容量的回收-Eviction-by-Size" class="headerlink" title="3.1. 基于容量的回收(Eviction by Size)"></a>3.1. 基于容量的回收(Eviction by Size)</h3><p>我们可以通过<code>maximumSize()</code>方法限制cache的size，如果cache达到了最大限制，oldest items 将会被回收。
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">whenCacheReachMaxSize_thenEviction</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       CacheLoader&lt;String, String&gt; loader;</span><br><span class="line">       loader = <span class="keyword">new</span> CacheLoader&lt;String, String&gt;() &#123;</span><br><span class="line">           <span class="meta">@Override</span></span><br><span class="line">           <span class="function"><span class="keyword">public</span> String <span class="title">load</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;;</span><br><span class="line">       LoadingCache&lt;String, String&gt; cache;</span><br><span class="line">       cache = CacheBuilder.newBuilder().maximumSize(<span class="number">3</span>).build(loader);</span><br><span class="line"></span><br><span class="line">       cache.getUnchecked(<span class="string">"first"</span>);</span><br><span class="line">       cache.getUnchecked(<span class="string">"second"</span>);</span><br><span class="line">       cache.getUnchecked(<span class="string">"third"</span>);</span><br><span class="line">       cache.getUnchecked(<span class="string">"forth"</span>);</span><br><span class="line">       assertEquals(<span class="number">3</span>, cache.size());</span><br><span class="line">       assertNull(cache.getIfPresent(<span class="string">"first"</span>));</span><br><span class="line">       assertEquals(<span class="string">"FORTH"</span>, cache.getIfPresent(<span class="string">"forth"</span>));</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>我们也可以限制cache size通过定制<code>weight function</code>，以下为自定义<code>weight function</code>实现的限制cache size 的示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">whenCacheReachMaxWeight_thenEviction</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      CacheLoader&lt;String, String&gt; loader;</span><br><span class="line">      loader = <span class="keyword">new</span> CacheLoader&lt;String, String&gt;() &#123;</span><br><span class="line">          <span class="meta">@Override</span></span><br><span class="line">          <span class="function"><span class="keyword">public</span> String <span class="title">load</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">              <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line">      Weigher&lt;String, String&gt; weighByLength;</span><br><span class="line">      weighByLength = <span class="keyword">new</span> Weigher&lt;String, String&gt;() &#123;</span><br><span class="line">          <span class="meta">@Override</span></span><br><span class="line">          <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">weigh</span><span class="params">(String key, String value)</span> </span>&#123;</span><br><span class="line">              <span class="keyword">return</span> value.length();</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line">      LoadingCache&lt;String, String&gt; cache;</span><br><span class="line">      cache = CacheBuilder.newBuilder()</span><br><span class="line">              .maximumWeight(<span class="number">16</span>)</span><br><span class="line">              .weigher(weighByLength)</span><br><span class="line">              .build(loader);</span><br><span class="line"></span><br><span class="line">      cache.getUnchecked(<span class="string">"first"</span>);</span><br><span class="line">      cache.getUnchecked(<span class="string">"second"</span>);</span><br><span class="line">      cache.getUnchecked(<span class="string">"third"</span>);</span><br><span class="line">      cache.getUnchecked(<span class="string">"last"</span>);</span><br><span class="line">      assertEquals(<span class="number">3</span>, cache.size());</span><br><span class="line">      assertNull(cache.getIfPresent(<span class="string">"first"</span>));</span><br><span class="line">      assertEquals(<span class="string">"LAST"</span>, cache.getIfPresent(<span class="string">"last"</span>));</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-2-定时回收-Eviction-by-Time"><a href="#3-2-定时回收-Eviction-by-Time" class="headerlink" title="3.2. 定时回收(Eviction by Time)"></a>3.2. 定时回收(Eviction by Time)</h3><p>除了通过size来回收记录，我们也可以选择定时回收</p>
<p><code>CacheBuilder</code>提供两种定时回收的方法：</p>
<ul>
<li><code>expireAfterAccess(long, TimeUnit)</code>：缓存项在给定时间内没有被读/写访问，则回收。请注意这种缓存的回收顺序和基于大小回收一样。</li>
<li><code>expireAfterWrite(long, TimeUnit)</code>：缓存项在给定时间内没有被写访问（创建或覆盖），则回收。如果认为缓存数据总是在固定时候后变得陈旧不可用，这种回收方式是可取的。</li>
</ul>
<p>下面代码 将示例<code>expireAfterAccess</code>的用法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">whenEntryIdle_thenEviction</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">       CacheLoader&lt;String, String&gt; loader;</span><br><span class="line">       loader = <span class="keyword">new</span> CacheLoader&lt;String, String&gt;() &#123;</span><br><span class="line">           <span class="meta">@Override</span></span><br><span class="line">           <span class="function"><span class="keyword">public</span> String <span class="title">load</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;;</span><br><span class="line"></span><br><span class="line">       LoadingCache&lt;String, String&gt; cache;</span><br><span class="line">       cache = CacheBuilder.newBuilder()</span><br><span class="line">               .expireAfterAccess(<span class="number">2</span>, TimeUnit.MILLISECONDS)</span><br><span class="line">               .build(loader);</span><br><span class="line"></span><br><span class="line">       cache.getUnchecked(<span class="string">"hello"</span>);</span><br><span class="line">       assertEquals(<span class="number">1</span>, cache.size());</span><br><span class="line"></span><br><span class="line">       cache.getUnchecked(<span class="string">"hello"</span>);</span><br><span class="line">       Thread.sleep(<span class="number">300</span>);</span><br><span class="line"></span><br><span class="line">       cache.getUnchecked(<span class="string">"test"</span>);</span><br><span class="line">       assertEquals(<span class="number">1</span>, cache.size());</span><br><span class="line">       assertNull(cache.getIfPresent(<span class="string">"hello"</span>));</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-3-基于引用的回收-Reference-based-Eviction"><a href="#3-3-基于引用的回收-Reference-based-Eviction" class="headerlink" title="3.3.基于引用的回收(Reference-based Eviction)"></a>3.3.基于引用的回收(Reference-based Eviction)</h3><p>通过使用弱引用的键、或弱引用的值、或软引用的值，Guava Cache可以把缓存设置为允许垃圾回收：</p>
<ul>
<li>CacheBuilder.weakKeys()：使用弱引用存储键。当键没有其它（强或软）引用时，缓存项可以被垃圾回收。因为垃圾回收仅依赖恒等式（==），使用弱引用键的缓存用==而不是equals比较键。</li>
<li>CacheBuilder.softValues()：使用软引用存储值。软引用只有在响应内存需要时，才按照全局最近最少使用的顺序回收。考虑到使用软引用的性能影响，我们通常建议使用更有性能预测性的缓存大小限定（见上文，基于容量回收）。使用软引用值的缓存同样用==而不是equals比较值。</li>
</ul>
<h3 id="3-4-显式清除"><a href="#3-4-显式清除" class="headerlink" title="3.4.显式清除"></a>3.4.显式清除</h3><p>任何时候，你都可以显式地清除缓存项，而不是等到它被回收：</p>
<ul>
<li>个别清除：<code>Cache.invalidate(key)</code></li>
<li>批量清除：<code>Cache.invalidateAll(keys)</code></li>
<li>清除所有缓存项：<code>Cache.invalidateAll()</code></li>
</ul>
<h3 id="4-移除监听-RemovalNotification"><a href="#4-移除监听-RemovalNotification" class="headerlink" title="4.移除监听(RemovalNotification)"></a>4.移除监听(RemovalNotification)</h3><blockquote>
<p>通过CacheBuilder.removalListener(RemovalListener)，你可以声明一个监听器，以便缓存项被移除时做一些额外操作。缓存项被移除时，RemovalListener会获取移除通知[RemovalNotification]，其中包含移除原因[RemovalCause]、键和值。</p>
</blockquote>
<p><strong>请注意，RemovalListener抛出的任何异常都会在记录到日志后被丢弃[swallowed]。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">whenEntryRemovedFromCache_thenNotify</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       CacheLoader&lt;String, String&gt; loader;</span><br><span class="line">       loader = <span class="keyword">new</span> CacheLoader&lt;String, String&gt;() &#123;</span><br><span class="line">           <span class="meta">@Override</span></span><br><span class="line">           <span class="function"><span class="keyword">public</span> String <span class="title">load</span><span class="params">(<span class="keyword">final</span> String key)</span> </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;;</span><br><span class="line"></span><br><span class="line">       RemovalListener&lt;String, String&gt; listener;</span><br><span class="line">       listener = <span class="keyword">new</span> RemovalListener&lt;String, String&gt;() &#123;</span><br><span class="line">           <span class="meta">@Override</span></span><br><span class="line">           <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onRemoval</span><span class="params">(RemovalNotification&lt;String, String&gt; n)</span> </span>&#123;</span><br><span class="line">               <span class="keyword">if</span> (n.wasEvicted()) &#123;</span><br><span class="line">                   String cause = n.getCause().name();</span><br><span class="line">                   assertEquals(RemovalCause.SIZE.toString(), cause);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;;</span><br><span class="line"></span><br><span class="line">       LoadingCache&lt;String, String&gt; cache;</span><br><span class="line">       cache = CacheBuilder.newBuilder()</span><br><span class="line">               .maximumSize(<span class="number">3</span>)</span><br><span class="line">               .removalListener(listener)</span><br><span class="line">               .build(loader);</span><br><span class="line"></span><br><span class="line">       cache.getUnchecked(<span class="string">"first"</span>);</span><br><span class="line">       cache.getUnchecked(<span class="string">"second"</span>);</span><br><span class="line">       cache.getUnchecked(<span class="string">"third"</span>);</span><br><span class="line">       cache.getUnchecked(<span class="string">"last"</span>);</span><br><span class="line">       assertEquals(<span class="number">3</span>, cache.size());</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h2 id="5-刷新-Refresh-the-Cache"><a href="#5-刷新-Refresh-the-Cache" class="headerlink" title="5.刷新( Refresh the Cache)"></a>5.刷新( Refresh the Cache)</h2><p>刷新和回收不太一样。正如LoadingCache.refresh(K)所声明，刷新表示为键加载新值，这个过程可以是异步的。在刷新操作进行时，缓存仍然可以向其他线程返回旧值，而不像回收操作，读缓存的线程必须等待新值加载完成。</p>
<p>如果刷新过程抛出异常，缓存将保留旧值，而异常会在记录到日志后被丢弃[swallowed]。</p>
<p>重载CacheLoader.reload(K, V)可以扩展刷新时的行为，这个方法允许开发者在计算新值时使用旧的值。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">cache_reLoad</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    CacheLoader&lt;String, String&gt; loader;</span><br><span class="line">    loader = <span class="keyword">new</span> CacheLoader&lt;String, String&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> String <span class="title">load</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 重写reload方法可以定制自己的reload策略</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@param</span> oldValue</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">         * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> ListenableFuture&lt;String&gt; <span class="title">reload</span><span class="params">(String key, String oldValue)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">super</span>.reload(key, oldValue);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    LoadingCache&lt;String, String&gt; cache;</span><br><span class="line">    cache = CacheBuilder.newBuilder()</span><br><span class="line">            .build(loader);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>CacheBuilder.refreshAfterWrite(long, TimeUnit)</code>可以为缓存增加自动定时刷新功能。和<code>expireAfterWrite</code>相反，<code>refreshAfterWrite</code>通过定时刷新可以让缓存项保持可用，但请注意：缓存项只有在被检索时才会真正刷新（如果CacheLoader.refresh实现为异步，那么检索不会被刷新拖慢）。因此，如果你在缓存上同时声明expireAfterWrite和refreshAfterWrite，缓存并不会因为刷新盲目地定时重置，如果缓存项没有被检索，那刷新就不会真的发生，缓存项在过期时间后也变得可以回收。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">whenLiveTimeEnd_thenRefresh</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       CacheLoader&lt;String, String&gt; loader;</span><br><span class="line">       loader = <span class="keyword">new</span> CacheLoader&lt;String, String&gt;() &#123;</span><br><span class="line">           <span class="meta">@Override</span></span><br><span class="line">           <span class="function"><span class="keyword">public</span> String <span class="title">load</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">               <span class="keyword">return</span> key.toUpperCase();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;;</span><br><span class="line"></span><br><span class="line">       LoadingCache&lt;String, String&gt; cache;</span><br><span class="line">       cache = CacheBuilder.newBuilder()</span><br><span class="line">               .refreshAfterWrite(<span class="number">1</span>, TimeUnit.MINUTES)</span><br><span class="line">               .build(loader);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h2 id="6-处理空值-Handle-null-Values"><a href="#6-处理空值-Handle-null-Values" class="headerlink" title="6. 处理空值(Handle null Values)"></a>6. 处理空值(Handle null Values)</h2><blockquote>
<p>实际上Guava整体设计思想就是拒绝null的，很多地方都会执行com.google.common.base.Preconditions.checkNotNull的检查。 </p>
</blockquote>
<p>By default, Guava Cache will throw exceptions if you try to load a null value – as it doesn’t make any sense to cache a null.</p>
<p>But if null value means something in your code, then you can make good use of the Optional class as in the following example:
默认情况guava cache将会抛出异常，如果试图加载null value–因为cache null 是没有任何意义的。
但是如果null value 对你的代码而已有一些特殊的含义，你可以尝试用Optional来表达，像下面这个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">whenNullValue_thenOptional</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        CacheLoader&lt;String, Optional&lt;String&gt;&gt; loader;</span><br><span class="line">        loader = <span class="keyword">new</span> CacheLoader&lt;String, Optional&lt;String&gt;&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Optional&lt;String&gt; <span class="title">load</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> Optional.fromNullable(getSuffix(key));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        LoadingCache&lt;String, Optional&lt;String&gt;&gt; cache;</span><br><span class="line">        cache = CacheBuilder.newBuilder().build(loader);</span><br><span class="line"></span><br><span class="line">        assertEquals(<span class="string">"txt"</span>, cache.getUnchecked(<span class="string">"text.txt"</span>).get());</span><br><span class="line">        assertFalse(cache.getUnchecked(<span class="string">"hello"</span>).isPresent());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> String <span class="title">getSuffix</span><span class="params">(<span class="keyword">final</span> String str)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> lastIndex = str.lastIndexOf(<span class="string">'.'</span>);</span><br><span class="line">        <span class="keyword">if</span> (lastIndex == -<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> str.substring(lastIndex + <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h2 id="7-统计"><a href="#7-统计" class="headerlink" title="7. 统计"></a>7. 统计</h2><p><code>CacheBuilder.recordStats()</code>用来开启Guava Cache的统计功能。统计打开后，<code>Cache.stats()</code>方法会返回<code>CacheStats</code>对象以提供如下统计信息：</p>
<ul>
<li>hitRate()：缓存命中率；</li>
<li>averageLoadPenalty()：加载新值的平均时间，单位为纳秒；</li>
<li>evictionCount()：缓存项被回收的总数，不包括显式清除。</li>
</ul>
<p>此外，还有其他很多统计信息。这些统计信息对于调整缓存设置是至关重要的，在性能要求高的应用中我们建议密切关注这些数据。</p>
<h2 id="8-Notes"><a href="#8-Notes" class="headerlink" title="8. Notes"></a>8. Notes</h2><p>1.什么时候用get，什么时候用getUnchecked
官网文档说：
<div class="note primary"><p>If you have defined a CacheLoader that does not declare any checked exceptions then you can perform cache lookups using getUnchecked(K);
however care must be taken not to call getUnchecked on caches whose CacheLoaders declare checked exceptions.</p>
</div></p>
<p>字面意思是，如果你的CacheLoader没有定义任何checked Exception，那你可以使用getUnchecked。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>大侠劫富济贫啦！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/dempe/20180527112524.jpg" alt="DempeZheng WeChat Pay"/>
        </div>
      
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016-11-05-guava-cache.html" rel="next" title="Guava Cache 分析">
                <i class="fa fa-chevron-left"></i> Guava Cache 分析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017-03-28-netty-outofmemory.html" rel="prev" title="记一次netty内存溢出的问题(上)">
                记一次netty内存溢出的问题(上) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466"
               alt="DempeZheng" />
          <p class="site-author-name" itemprop="name">DempeZheng</p>
           
              <p class="site-description motion-element" itemprop="description">請更固執，將自己謀生與擅長的事情做到最好</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">68</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/dempeZheng" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://music.163.com/#/user/home?id=6758793" target="_blank" title="网易云音乐">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  网易云音乐
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/dempe" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.wolfbe.com/" title="朗度云" target="_blank">朗度云</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-使用场景"><span class="nav-number">1.</span> <span class="nav-text">1.使用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-如何使用Guava-Cache"><span class="nav-number">2.</span> <span class="nav-text">2.如何使用Guava Cache</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-回收策略"><span class="nav-number">3.</span> <span class="nav-text">3.回收策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-基于容量的回收-Eviction-by-Size"><span class="nav-number">3.1.</span> <span class="nav-text">3.1. 基于容量的回收(Eviction by Size)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-定时回收-Eviction-by-Time"><span class="nav-number">3.2.</span> <span class="nav-text">3.2. 定时回收(Eviction by Time)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-基于引用的回收-Reference-based-Eviction"><span class="nav-number">3.3.</span> <span class="nav-text">3.3.基于引用的回收(Reference-based Eviction)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-显式清除"><span class="nav-number">3.4.</span> <span class="nav-text">3.4.显式清除</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-移除监听-RemovalNotification"><span class="nav-number">3.5.</span> <span class="nav-text">4.移除监听(RemovalNotification)</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-刷新-Refresh-the-Cache"><span class="nav-number">4.</span> <span class="nav-text">5.刷新( Refresh the Cache)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-处理空值-Handle-null-Values"><span class="nav-number">5.</span> <span class="nav-text">6. 处理空值(Handle null Values)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-统计"><span class="nav-number">6.</span> <span class="nav-text">7. 统计</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-Notes"><span class="nav-number">7.</span> <span class="nav-text">8. Notes</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">DempeZheng</span>
</div>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("dhzMp0HdJLWMCrt04bwybWzH-gzGzoHsz", "gH6FmxJiUaVLLRXQDWpkkIVv");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

</body>
</html>
